package com.jy.appmarket.service;

import java.util.Calendar;
import java.util.List;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.telephony.TelephonyManager;

import com.jy.appmarket.R;
import com.jy.appmarket.activity.PhoneEssentialActivity;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.Settings;

public class NotificationService extends Service {

	private static final String TAG = "NotificationService";
	private static final long INTERVAL_MILLIS = 1000 * 60 * 60;
	private static final int NOTIFICATION_ID = 111111;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		LogUtil.d(TAG, "------------>NotificationService onStartCommand");
		if (Settings.ReadIsOpen(this)) {
			cancelAlarmmanager();
			stopSelf();
			return START_NOT_STICKY;
		}
		doWork();
		stopSelf();
		return START_STICKY;
	}

	private void doWork() {
		if (getIMSI() == null) {
			return;
		}

		int currentTime = Settings.readCounts(this) + 1;
		Settings.writeCounts(this, currentTime);

		if (currentTime > 72) {
			cancelAlarmmanager();
			return;
		}

		if ((currentTime >= 24 && currentTime <= 72 && inSpecifyTime() && needShowNotification(currentTime))
				|| currentTime == 1) {
			Settings.WriteLastNotification(this, currentTime);
			showNotification();
		}
	}

	public static void startNotificationService(Context context, long delayTime) {
		if (isServiceRunning(context)) {
			LogUtil.i(TAG, "notification service is running!");
			return;
		}
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, NotificationService.class);
		PendingIntent pIntent = PendingIntent.getService(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delayTime,
				INTERVAL_MILLIS, pIntent);
	}

	private void cancelAlarmmanager() {
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		Intent i = new Intent(this, NotificationService.class);
		PendingIntent pIntent = PendingIntent.getService(this, 1, i, PendingIntent.FLAG_UPDATE_CURRENT);
		am.cancel(pIntent);
	}

	public static boolean isServiceRunning(Context context) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(100);
		if (serviceList == null || serviceList.isEmpty()) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(NotificationService.class.getName())) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	private String getIMSI() {
		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		return telephonyManager.getSubscriberId();
	}

	private boolean inSpecifyTime() {
		Calendar calendar = Calendar.getInstance();
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
        return hour >= 19 && hour < 22;

    }

	/**
	 * 保证一天只可能显示一次Notification
	 * 
	 * @param currentTime
	 *            累计插有SIM卡的时间
	 * 
	 */
	private boolean needShowNotification(int currentTime) {
		int lastTime = Settings.ReadLastNotification(this);
        return lastTime == 0 || currentTime - lastTime > 20;
	}

	private void showNotification() {
		String content = getString(R.string.goto_phoneessential_check_detail);
		NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
		builder.setSmallIcon(R.drawable.notify_icon).setStyle(new NotificationCompat.BigTextStyle().bigText(content))
				.setAutoCancel(true).setContentTitle(getResources().getString(R.string.app_requisite))
				.setContentText(content).setTicker(content).setDefaults(Notification.DEFAULT_SOUND);

		Intent intent = new Intent(this, PhoneEssentialActivity.class);
		intent.putExtra(PhoneEssentialActivity.COME_FROM, PhoneEssentialActivity.FROM_NOTIFICATION);

		PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
		builder.setContentIntent(pi);

		NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		nm.notify(NOTIFICATION_ID, builder.build());
	}
}
